import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

import Entity.MessageDTO;

@WebServlet(urlPatterns = {"/Login_Check"})
public class Login_Check extends HttpServlet{
    private static final EntityManagerFactory entityManagerFactory;
    private static final String PERSISTENCE_UNIT_NAME = "MyJPADemoPU";

    static {
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    }

    private EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }

    protected void login_check(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException
    {
        String loginname = req.getParameter("loginname");
        String loginpassword = req.getParameter("loginpassword");
        EntityManager em = getEntityManager();
        EntityTransaction tx = em.getTransaction();
        boolean flag=false;
        MessageDTO message=null;
        //判断登录信息是否存在
        try {
            Query query = em.createQuery("select mes from MessageDTO mes where mes.name = :name");
            query.setParameter("name",loginname);
            List list = query.getResultList();
            if (list.size() != 0) {
                for (Object i : list) {
                    message = (MessageDTO) i;
                    if (message.getname().equals(loginname)&&message.getpassword().equals(loginpassword)) {
                        flag = true;
                        break;
                    }
                }
            }
            if (flag) {
                req.getSession().setAttribute("LocalUser", message);
                resp.sendRedirect("userinfo.jsp");
            } else {
                System.out.println("该用户不存在，请先注册");
                resp.sendRedirect("error.jsp");
            }
        }catch(Exception e)
        {
            resp.sendRedirect("error.jsp");
        }finally {
            em.close();
        }
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        login_check(req,resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

}